package com.example.flashsales.service.impl;

import com.example.flashsales.entity.dto.RefundDetailsDto;
import com.example.flashsales.entity.dto.RefundDto;
import com.example.flashsales.entity.pojo.ReturnOrder;
import com.example.flashsales.entity.pojo.ReturnOrderDetails;
import com.example.flashsales.entity.vo.GoodsVo;
import com.example.flashsales.entity.vo.OrdersVo;
import com.example.flashsales.entity.vo.ReturnOrderDetailsVo;
import com.example.flashsales.entity.vo.ReturnOrderVo;
import com.example.flashsales.mappers.RefundMapper;
import com.example.flashsales.service.RefundService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Service
public class RefundServiceImpl implements RefundService {

    @Autowired
    UserServiceImpl userService;

    @Autowired
    UserCostRecordServiceImpl userCostRecordService;

    @Autowired
    AdminCostRecordServiceImpl adminCostRecordService;

    @Autowired
    RefundMapper refundMapper;

    @Autowired
    GoodsServiceImpl goodsService;

    @Autowired
    OrderServiceImpl orderService;

    /**
     * 添加一条退款纪录
     * @param refundDto 退款订单
     * @param refundDetailsDtoList 退款细节
     * @return 返回是否提交成功
     */
    @Override
    @Transactional
    public String refund(RefundDto refundDto, List<RefundDetailsDto> refundDetailsDtoList) {
        //退款订单
        final List<ReturnOrder> returnOrders = refundMapper.viewRefundByOrderId(refundDto.getOrderId());
        if (returnOrders != null){
            for (ReturnOrder returnOrder : returnOrders) {
                //根据退款订单id获取细节
                final List<ReturnOrderDetails> returnOrderDetails = refundMapper.viewRefundDetails(returnOrder.getId());
                for (ReturnOrderDetails returnOrderDetail : returnOrderDetails) {
                    for (RefundDetailsDto refundDetailsDto : refundDetailsDtoList) {
                        if (refundDetailsDto.getGoodsId() == returnOrderDetail.getGoodsId()){
                            return "提交失败，已存在订单";
                        }
                    }
                }
            }
        }
        if (refundMapper.refund(refundDto) > 0) {
            //退款订单id
            long refundId = refundDto.getId();
            for (RefundDetailsDto refundDetailsDto : refundDetailsDtoList) {
                refundDetailsDto.setReturnOrderId(refundId);
                final GoodsVo goodsVo = goodsService.viewGoodsMessage(refundDetailsDto.getGoodsId());
                refundDetailsDto.setMoney(goodsVo.getPrice()*refundDetailsDto.getCount());
                if (refundMapper.addDetails(refundDetailsDto) <= 0) {
                    return "提交失败";
                }
            }
            return "提交成功";
        }
        return "提交失败";
    }


    /**
     * 查看某条的退款
     * @param refundId 退款订单id
     * @return 返回退款订单视图对象
     */
    @Override
    public ReturnOrderVo viewRefundDetails(long refundId) {
        final List<ReturnOrderDetails> returnOrderDetails = refundMapper.viewRefundDetails(refundId);
        List<ReturnOrderDetailsVo> returnOrderDetailsVos = new ArrayList<>();
        for (ReturnOrderDetails returnOrderDetail : returnOrderDetails) {
            ReturnOrderDetailsVo returnOrderDetailsVo = new ReturnOrderDetailsVo();
            BeanUtils.copyProperties(returnOrderDetail,returnOrderDetailsVo);
            if (returnOrderDetailsVo.getState() == 0){
                returnOrderDetailsVo.setSState("退款中");
            }else if (returnOrderDetailsVo.getState() == 1){
                returnOrderDetailsVo.setSState("退款成功");
            }else if (returnOrderDetailsVo.getState() == 2){
                returnOrderDetailsVo.setSState("退款失败");
            }else {
                returnOrderDetailsVo.setSState("未知");
            }
            GoodsVo goodsVo = goodsService.viewGoodsMessage(returnOrderDetailsVo.getGoodsId());
            returnOrderDetailsVo.setGoodsName(goodsVo.getName());
            returnOrderDetailsVos.add(returnOrderDetailsVo);
        }
        ReturnOrderVo returnOrderVo = new ReturnOrderVo();
        returnOrderVo.setReturnOrderDetailsVos(returnOrderDetailsVos);
        final ReturnOrder returnOrder = refundMapper.viewRefund(refundId);
        if (returnOrder != null){
            BeanUtils.copyProperties(returnOrder,returnOrderVo);
            if (returnOrderVo.getState() == 0){
                returnOrderVo.setSState("退款中");
            }else if (returnOrderVo.getState() == 1){
                returnOrderVo.setSState("退款完成");
            }else if (returnOrderVo.getState() == 2){
                returnOrderVo.setSState("退款失败");
            }else {
                returnOrderVo.setSState("未知");
            }
            return returnOrderVo;
        }
        return null;
    }


    /**
     * 查看所有的退款
     * @return
     */
    @Override
    public List<ReturnOrderVo> viewAllRefund(int page,int num) {
       List<Integer> refundIds =  refundMapper.viewRefundId((page-1)*num,num);
        List<ReturnOrderVo> returnOrderVos = new ArrayList<>();
        for (Integer refundId : refundIds) {
            returnOrderVos.add(viewRefundDetails(refundId));
        }
        return returnOrderVos;
    }


    /**
     * 按类型查看
     * @return
     */
    @Override
    public List<ReturnOrderVo> viewRefundByState(int state,int page,int num) {
        List<Integer> integers = refundMapper.viewRefundByState(state,(page-1)*num,num);
        List<ReturnOrderVo> returnOrderVos = new ArrayList<>();
        for (Integer integer : integers) {
            returnOrderVos.add(viewRefundDetails(integer));
        }
        return returnOrderVos;
    }

    /**
     * 用户查看自己的退款所有
     * @param userId
     * @return
     */
    @Override
    public List<ReturnOrderVo> viewAllRefundByUser(long userId) {
        //订单id
        final List<Integer> list = orderService.viewOrderIdByUser(userId);
        List<ReturnOrderVo> returnOrderVos = new ArrayList<>();
        List<Integer> list1 = new ArrayList<>();
        //退款订单集合
        for (Integer integer : list) {
            final List<Integer> list2 = refundMapper.viewIdByOrderId(integer);
            if (list2 != null || !list.isEmpty()){
                for (Integer integer1 : list2) {
                    list1.add(integer1);
                }
            }
        }
        for (Integer integer : list1) {
            ReturnOrderVo returnOrderVo = viewRefundDetails(integer);
            if (returnOrderVo != null) {
                returnOrderVos.add(returnOrderVo);
            }
        }
        return returnOrderVos;
    }


    /**
     * 用户按状态查看
     * @param userId
     * @param state
     * @return
     */
    @Override
    public List<ReturnOrderVo> viewAllRefundByUserAndState(long userId, long state) {
        final List<Integer> list = orderService.viewOrderIdByUser(userId);
        List<ReturnOrderVo> returnOrderVos = new ArrayList<>();
        for (Integer integer : list) {
            final List<Integer> list1 = refundMapper.viewAllRefundByUserAndState(state, integer);
            for (Integer integer1 : list1) {
                ReturnOrderVo returnOrderVo = viewRefundDetails(integer1);
                if (returnOrderVo != null) {
                    returnOrderVos.add(returnOrderVo);
                }
            }
        }
        return returnOrderVos;
    }


    /**
     * 修改订单细节的状态
     * @param state 状态 状态 0退款审核中，1退款完成，退款不通过
     * @param detailsId 退款订单细节id
     * @return 返回是否退款成功
     */
    @Override
    @Transactional
    public boolean updateRefundState(int state, long detailsId,int adminId) {
        if (refundMapper.updateDetailsState(detailsId,state) > 0) {
            final long l = refundMapper.viewRefundDetailsInRefundId(detailsId);
            final ReturnOrderVo returnOrderVo = viewRefundDetails(l);
            //细节集合
            final List<ReturnOrderDetailsVo> returnOrderDetailsVos = returnOrderVo.getReturnOrderDetailsVos();
            boolean b = true;
            double money = 0.0;
            for (ReturnOrderDetailsVo returnOrderDetailsVo : returnOrderDetailsVos) {
                if (returnOrderDetailsVo.getState() == 0){
                    b = false;
                }
                if (returnOrderDetailsVo.getState() == 1){
                    money = money + returnOrderDetailsVo.getMoney();
                }
            }
            if (b){
                if (refundMapper.updateState(state,l,adminId) > 0) {
                    //修改完了退款订单的状态
                    //增加用户的流水纪录
                    if (money > 0.0){
                        final OrdersVo ordersVo = orderService.viewOrder(returnOrderVo.getOrderId()).get(0);
                        if (userCostRecordService.addRecord(ordersVo.getUserId(),returnOrderVo.getOrderId(),money,1,adminId)) {
                            //增加用户余额
                            if (userService.updateMoneyInUser(ordersVo.getUserId(),money)) {
                                //增加商家的流水纪录
                                if (adminCostRecordService.addCostRecord(3,money*-1).equals("添加成功")) {
                                    return true;
                                }
                            }
                        }
                        return false;
                    }
                    return true;
                }
            }
            return true;
        }

        return false;
    }

    /**
     * 取消退款订单
     * @param refundId
     * @return
     */
    @Override
    public int cancelRefundOrder(Long refundId) {
        return refundMapper.cancelRefundOrder(refundId);
    }

    /**
     * 根据类型查看总数
     * @param state
     * @return
     */
    public Integer viewCountByState(Integer state) {
        return refundMapper.viewCountByState(state);
    }

    /**
     * 查看所有数量
     * @return
     */
    public Integer viewCount() {
        return refundMapper.viewCount();
    }

//    /**
//     * 修改订单状态
//     * @param state 状态
//     * @param refundId 订单id
//     * @param adminId 审核人员id
//     * @return
//     */
//    @Override
//    public boolean updateState(int state, long refundId, int adminId) {
////        final ReturnOrderVo returnOrderVo = viewRefundDetails(refundId);
////        //细节集合
////        final List<ReturnOrderDetailsVo> returnOrderDetailsVos = returnOrderVo.getReturnOrderDetailsVos();
////        for (ReturnOrderDetailsVo returnOrderDetailsVo : returnOrderDetailsVos) {
////            if (returnOrderDetailsVo.getState() == 0){
////                return false;
////            }
////        }
////        if (refundMapper.updateState(state,refundId,adminId) > 0) {
////            return true;
////        }
//        return false;
//    }
}
